const { FormatJson } = require("../utils/tool");
const validata = require("validate.js");
const { ValidationError, DataFaildError } = require("../utils/errors");
const { addProject, getProject, deleteProject, updateProject } = require("../Dao/projectsDao");
// 获取所有项目
module.exports.getProjectServices = async function () {
    let result = await getProject();
    result.rows.sort((a, b) => a.order - b.order);
    for (const items of result.rows) {
        delete items.deletedAt;
    }
    result = {
        total: result.count,
        rows: result.rows
    }
    return FormatJson(0, "", result);
}

// 添加项目
module.exports.addProjectServices = async function (ProjectInfos) {
    ProjectInfos.description = JSON.stringify(ProjectInfos.description);
    const ProjectRule = {
        description: {
            presence: {
                allowEmpty: false
            },
            type: "string"
        },
        name: {
            presence: {
                allowEmpty: false
            },
            type: "string"
        },
        url: {
            presence: {
                allowEmpty: false
            },
            type: "string"
        },
        github: {
            presence: {
                allowEmpty: false
            },
            type: "string"
        },
        thumb: {
            presence: {
                allowEmpty: false
            },
            type: "string"
        },
        order: {
            presence: {
                allowEmpty: false
            },
            numericality: {
                strict: false
            }
        }
    }
    const isAdoPt = validata.validate(ProjectInfos, ProjectRule);
    console.log(isAdoPt);
    if (!isAdoPt) {
        const result = await addProject(ProjectInfos);
        console.log(result)
        delete result.deletedAt;
        return FormatJson(0, "", result);
    } else {
        throw new DataFaildError(isAdoPt);
    }
}

//修改项目
module.exports.updateProjectServices = async function (id, info) {
    const data = await updateProject(id, info);
    delete data.deletedAt;
    return FormatJson(0, "", [data])
}

// 删除项目
module.exports.deleteProjectServices = async function (id) {
    return await deleteProject(id) > 0 ? FormatJson(0, "", true) : FormatJson(0, "", false);
}